<script setup lang="ts">
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const userStore = useUserStore()

const router = useRouter()

const activeIndex = ref('')
const handleSelect = (key: string, keyPath: string[]) => {
  if (key == '#') return
  changeActiveIndex()

  router.push('/' + key)
  // console.log(key, keyPath)
}

const changeActiveIndex = () => {
  // 获取当前路由路径
  const path = router.currentRoute.value.path
  // 获取路径中的最后一个部分
  const lastPart = path.split('/').pop()
  // 设置默认激活的菜单项
  activeIndex.value = String(lastPart)
}

const goToSetting = () => {
  router.push('/setting')
}

const logout = () => {
  userStore.logout()
  ElMessage({ type: 'success', message: '退出登录成功' })
  router.push('/')
}

changeActiveIndex()
</script>

<template>
  <div id="view">
    <el-container style="height: 100%">
      <el-header class="header">
        <el-menu
          :default-active="activeIndex"
          class="header-menu"
          mode="horizontal"
          :ellipsis="false"
          @select="handleSelect"
        >
          <el-menu-item index="#">
            <div class="logo-item">
              <img src="/images/logo.png" alt="logo" class="menu-logo" />
              <span class="logo-text">跨境电商平台</span>
            </div>
          </el-menu-item>
          <el-menu-item index="home">首页</el-menu-item>
          <el-menu-item index="products">商品</el-menu-item>
          <el-menu-item index="orders">订单</el-menu-item>
          <el-menu-item index="logistics/providers">物流商</el-menu-item>
          <el-menu-item index="logistics/orders">物流商订单</el-menu-item>
          <el-menu-item index="dsf">第三方授权</el-menu-item>
          <el-menu-item index="setting">设置</el-menu-item>

          <el-sub-menu index="user" class="user">
            <template #title>
              <el-icon><User /></el-icon>
              {{ userStore.userInfo.request_data.username }}</template
            >
            <el-menu-item index="1" @click="goToSetting">账号设置</el-menu-item>
            <el-menu-item index="2" @click="logout">登出</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-header>
      <el-main class="main"><router-view></router-view></el-main>
    </el-container>
  </div>
</template>

<style scoped lang="scss">
#view {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;

  .header {
    // background-color: pink;
    padding: 0;

    .header-menu {
      width: 100%;
      margin: 0;
      padding: 0;

      .logo-item {
        display: flex;
        align-items: center;

        .menu-logo {
          width: 32px;
          height: 32px;
          margin-right: 16px;
        }
      }

      .user {
        position: absolute;
        right: 16px;
      }
    }
  }

  .main {
    height: 100%;
  }
}
</style>
